package security;

import utils.SessionData;
import entity.User;
import entity.UserRole;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import utils.ServletUtil;

@WebFilter(filterName = "BackendFilter",
            urlPatterns = {"/backend/*"},
            dispatcherTypes = {DispatcherType.FORWARD,
                                DispatcherType.ERROR,
                                DispatcherType.REQUEST,
                                DispatcherType.INCLUDE},
            initParams = {@WebInitParam(name="error_page", value="../Home")})
public class BackendFilter implements Filter {
    
    private FilterConfig filterConfig = null;
    
    @Override
    public void init(FilterConfig filterConfig) {        
        this.filterConfig = filterConfig;
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        
        SessionData sessionData = ServletUtil.getSessionData((HttpServletRequest)request);
        User user = sessionData.getUser();
        
        AuthorizationManager authManager = new AuthorizationManager();
        boolean isAuthorized = authManager.isAuthorized(user, UserRole.BACKEND_USER);
        
        if (isAuthorized) {
            chain.doFilter(request, response);
        }
        else {
            if (filterConfig != null) { 
                String errorPage = filterConfig.getInitParameter("error_page");
                HttpServletResponse res = (HttpServletResponse)response;
                res.sendRedirect(errorPage);
            }
        }
    }

    @Override
    public void destroy() {
    }
}
